<?php


namespace App\Services\Admin;

use App\Models\Permission;
use App\Models\Role;
use App\Models\RolePermission;
use Illuminate\Support\Facades\DB;

class PermissionService
{
    protected $permission;

    public function __construct(Permission $permission)
    {
        $this->permission = $permission;
    }

    /**
     * 获取角色菜单
     * @param $roleId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMenuList($roleId)
    {
        $role = Role::where(['id' => $roleId, 'status' => 1])->first();
        if (!$role) {
            return Error('角色不存在或该角色已被禁用！', 401);
        }
        $menu = [];
        $menu = $this->get_menu_by_role($roleId);
        return success('获取成功！', $menu);
    }

    /**
     * 获取角色对应菜单权限
     * @param $roleId
     * @return array
     */
    private function get_menu_by_role($roleId)
    {
        if ($roleId == 1) {
            $menu = Permission::all();
        } else {
            $menu = array();
            $role_permission = RolePermission::where('role_id', $roleId)->get();
            if (count($role_permission)) {
                foreach ($role_permission as $item) {
                    $permission = Permission::find($item->permission_id);
                    $ids[] = $item->permission_id;

                    //含子菜单添加父菜单
                    if (!in_array($permission->parent_id,$ids)){
                        $ids[] = $permission->parent_id;
                    }
                }
                $menu = Permission::whereIn('id', $ids)->get();
            }
        }
        return $this->init_menu($menu, 0,[1, 2]);
    }

    /**
     * 获取所有菜单
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllMenu(){
        $menu = Permission::all();
        $tree = $this->init_menu($menu, 0,[1, 2, 3]);
        return Success('获取成功！', $tree);
    }

    /**
     * 获取所有菜单权限码
     * @return array
     */
    public static function allMenuCode(){
        $code = array();
        $menus = Permission::where('parent_id',0)
            ->get();
        if (count($menus)){
            foreach ($menus as $menu){
                $code[] = $menu->id;
            }
        }
        return $code;
    }

    /**
     * 获取指定角色权限码
     * @param $roleId
     * @return array
     */
    public static function menuCodeRole($roleId){
        $code = array();
        $menus = RolePermission::where('role_id', $roleId)
            ->get();
        if (count($menus)){
            foreach ($menus as $menu){
                $code[] = $menu->permission_id;
            }
        }
        return $code;
    }

    /**
     * 添加/编辑菜单
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrUpdateMenu($params){
        if (isset($params['id'])){
            $menu = Permission::find($params['id']);
        }else{
            $menu = new Permission();
        }
        unset($params['id']);

        //目录路由由标识生成
        if ($params['menu_type'] == 1){
            $params['path'] = '/' . $params['permission'];
        }
        foreach ($params as $k => $v){
            $menu->$k = $v;
        }

        if ($menu->save()){
            return Success('操作成功！');
        }else{
            return Error('操作失败！');
        }
    }

    public function deleteMenu($id){
        $childMenu = Permission::where('parent_id',$id)
            ->first();
        if ($childMenu){
            return Error('操作失败，该菜单下含有子菜单未删除！');
        }

        //同时删除角色对应菜单
        try {
            DB::beginTransaction();
            Permission::destroy($id);
            RolePermission::where('permission_id',$id)->delete();
            DB::commit();

            return Success('删除成功');
        }catch (\Exception $exception){
            DB::rollBack();
            return Error('删除失败！');
        }
    }

    /**
     * 递归解析菜单结构
     * @param $menu
     * @return array
     */
    private function init_menu($data, $pId, $menu_type)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            $v->meta = [
              'icon' => $v->icon,
              'title' => $v->title,
            ];

            if ($v->parent_id == $pId && in_array($v->menu_type, $menu_type)) {
                $children = $this->init_menu($data, $v->id,$menu_type);
                if ($children){
                    $v->children = $children;
                }

                //排序
                $sort[] = $v->order_no;
                $tree[] = $v;
                array_multisort($sort,SORT_NUMERIC,SORT_ASC,$tree);
                unset($data[$k]);
            }
        }
        return $tree;
    }
}
